/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */


package org.apache.skywalking.apm.agent.core.jvm.cpu;

import org.apache.skywalking.apm.network.common.CPU;

/**
 * The unit of CPU usage is 1/10000. The backend is using `avg` func directly, and query for percentage requires this
 * unit.
 *
 * @author wusheng
 */
public abstract class CPUMetricsAccessor {
    private long lastCPUTimeNs;    //进程占用 CPU 时长，单位：纳秒。
    private long lastSampleTimeNs; //最后采样时间，单位：纳秒
    private final int cpuCoreNum;  //CPU 的核数量

    public CPUMetricsAccessor(int cpuCoreNum) {
        this.cpuCoreNum = cpuCoreNum;
    }

    protected void init() {
        lastCPUTimeNs = this.getCpuTime();
        lastSampleTimeNs = System.nanoTime();
    }

    /**
     * 通过 OperatingSystemMXBean 对象
     * 获得 JVM 进程占用 CPU 总时长
     * @return
     */
    protected abstract long getCpuTime();

    public CPU getCPUMetrics() {

        //采样
        long cpuTime = this.getCpuTime();

        //计算：本次获取的cpu占用时间 - 上次占用cpu的时间
        long cpuCost = cpuTime - lastCPUTimeNs;
        long now = System.nanoTime();

        try {
            CPU.Builder cpuBuilder = CPU.newBuilder();
      //       now （本次取样时间）- lastSampleTimeNs（上次取样时间），获得 JVM 进程启动总时长
//          通过相减，解决偏差：     CPUMetricAccessor 不是在 JVM 启动时就进行计算，而是在调用的时候，进行计算
//
            //计算 JVM 进程占用 CPU 率
            return cpuBuilder.setUsagePercent(cpuCost * 1.0d / ((now - lastSampleTimeNs) * cpuCoreNum) * 100).build();
        } finally {
            lastCPUTimeNs = cpuTime;//记录：上次占用cpu的时间
            lastSampleTimeNs = now;//记录： 上次取样时间
        }
    }
}
